Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
@zilliqa-js/account
Advanced tools
Classes for managing accounts and account-related actions.
export interface TxReceipt {
success: boolean;
cumulative_gas: number;
}
interface TxParams {
version: number;
toAddr: string;
amount: BN;
gasPrice: BN;
gasLimit: Long;
code?: string;
data?: string;
receipt?: TxReceipt;
nonce?: number;
pubKey?: string;
signature?: string;
}
When you give nonce
, you should give pubKey
together.
Account
Class for managing an account (i.e., a private/public keypair).
Account(privateKey: string, nonce?: number): Account
privateKey
: string
- hex-encoded private keynonce
: number
(optional) - the current nonceAccount
- an Account
instance.privateKey: string
publicKey: string
address: string
nonce: number
static fromFile(file: string, passphrase: string): Promise<Account>
Generates an account from any JSON-encoded string that complies with the Web3 Secret Storage definition.
file
: string
- JSON-encoded string containing the keystore file.passphrase
: string
- passphrase used to encrypt the file.Promise<Account>
- an Account
instance, initialised with the details
provided by the keystore file.toFile(passphrase: string, kdf: 'pbkdf2' |'scrypt' = 'scrypt'): Promise<Account>
Encrypts and JSON-encodes the account. Complies with the Web3 Secret Storage definition.
passphrase
: string
- passphrase used to encrypt the file.kdf
: 'pbkdf2' | 'scrypt'
- the key derivation function to use for
encryption.Promise<string>
- the JSON-encoded string of the keystore file.signTransaction(bytes: Buffer): string
Signs arbitrary bytes (most often transactions) using a Schnorr signing scheme.
bytes
: Buffer
- a Buffer
of the protobuf
encoded transaction bytes.string
- hex-encoded signature over the bytes, using the instance private
key.Wallet
Class for managing multiple accounts.
Wallet(provider: Provider, accounts?: Account[] = []): Wallet
provider
: Provider
- a Provider instance (see @zilliqa-js/core
).
Required for signing.accounts
: Account[]
(optional) - an array of Account
instances to
pre-populate the wallet with.Wallet
accounts: { [address: string]: Account }
An object consisting of address: Account
KV pairs. By default, an empty
object.
defaultAccount: Account
The default account used for signing transactions. By default, undefined
. It
is set to the 0
-indexed account when a Wallet
instance is constructed.
create(): void
Creates a new keypair with a randomly-generated private key. The new account is
accessible by address. This method mutates the Wallet
instance.
None
string
- address of the new account.addByPrivateKey(privateKey: string): string
Adds an Account
to the Wallet
.
privateKey
: string
- hex-encoded private key.string
- the corresponing address, computer from the private key.addByKeystore(keystore: string, passphrase: string): Promise<string>
Adds an account by keystore. This method is asynchronous and returns a
Promise<string>
, in order not to block on the underlying decryption operation.
keystore
: string
- JSON-encoded keystore file.passphrase
: string
- the passphrase used to encode the keystore file.Promise<string>
- the corresponding address.addByMnemonic(phrase: string, index: number = 0): string
Adds an Account
by use of a mnemonic as specified in BIP-32 and BIP-39
phrase
: string
- the 12-word mnemonic to use.index
: number
(Optional) - the index of the child key.string
- the corresponding address.export(address: string, passphrase, string, kdf: 'pbkdf2' | 'scrypt'): Promise<string>
Account
to a keystore file, encrypted with a passphrase.address
: string
- the address of the selected account.passphrase
: string
- the passphrase to encrypt the Account
with.kdf
: 'pbkdf2' | 'scrypt'
- key derivation function.Promise<string>
- the JSON-encoded keystore file.remove(address: string): boolean
Account
to a keystore file, encrypted with a passphrase.address
: string
- the address of the account to remove.boolean
- whether the Account
was successfully removed.setDefault(address: string): void
Sets the default account to sign with.
address
: string
- the address of the account to set as default.void
sign(transaction: Transaction, offlineSign?: boolean): Promise<Transaction>
Sign a Transaction
with the default Account
. This method is asynchronous as
it will attempt to obtain the nonce
from the Provider
. There is an offline
mode that can be activated manually by setting the optional offlineSign
parameter.
transaction
: Transaction
- a Transaction
instance.offlineSign
: boolean
(optional) - toggles offline signing on/off. Defaults
to false
if the field is not set. If explicitly set to true
, offline mode
is used and does not require internet connection to sign a transaction.object.
Promise<Transaction>
- a signed transaction.signWith(transaction: Transaction, address: string, offlineSign?: boolean): Promise<Transaction>
Sign a Transaction
with the chosen Account
. This method is asynchronous as
it will attempt to obtain the nonce
from the Provider
. There is an offline
mode that can be activated manually by setting the optional offlineSign
parameter.
transaction
: Transaction
- a Transaction
instance.address
: string
- the address of the Account
to be used for signing.offlineSign
: boolean
(optional) - toggles offline signing on/off. Defaults
to false
if the field is not set. If explicitly set to true
, offline mode
is used and does not require internet connection to sign a transaction.object.
Promise<Transaction>
- a signed transaction.signBatch(txList: Transaction[]): Promise<Transaction[]>
Sign a list of Transaction
with the default Account
. This method is
asynchronous as it will attempt to obtain the nonce
from the Provider
.
txList
: Transaction[]
- a list of Transaction
instances.Promise<Transaction[]>
- a list of signed transactions.// zilliqa, wallet obj declaration omitted for clarity
let txList = [];
for (let i = 0; i < 2; i++) {
// create a new transaction object
const tx = zilliqa.transactions.new(
{
version: VERSION,
toAddr: "0xA54E49719267E8312510D7b78598ceF16ff127CE",
amount: new BN(units.toQa("1", units.Units.Zil)),
gasPrice: units.toQa("2000", units.Units.Li),
gasLimit: Long.fromNumber(1),
},
false
);
txList.push(tx);
}
// sign the batch transactions sequentially
const batchResult = await zilliqa.wallet.signBatch(txList);
for (const signedTx of batchResult) {
// nonce must be different
console.log("The signed transaction nonce is: %o", signedTx.nonce);
console.log("The signed transaction signature is: %o\n", signedTx.signature);
}
Transaction
A class that represents a single Transaction
on the Zilliqa network. It is a
functor. Its purpose is to encode the possible states a Transaction can be in:
Confirmed, Rejected, Pending, or Initialised (i.e., not broadcasted).
bytes: Buffer
A getter protobuf
that returns a Buffer
of protobuf
-encoded bytes. This is
a convenience member that allows a Transaction
to be signed easily.
senderAddress: string
A getter than computes the address of the Transaction
sender. If there is no
sender public key set, returns 0x00000000000000000000000000000000000000000000
.
txParams: TxParams
A getter that returns the current TxParams
.
static confirm(params: TxParams, provider: Provider): Transaction
Instantiates a Transaction
in Confirmed
state.
params
: TxParams
- core fields to initialise the Transaction
with.provider
: Provider
- a Provider
instance.Transaction
- the newly-Instantiated Transaction
.import { HTTPProvider } from "@zilliqa-js/core";
import { Transaction } from "@zilliqa-js/account";
const txParams = {
version: 0,
toAddr: "20_byte_hex_string",
amount: new BN(8),
gasPrice: new BN(100),
gasLimit: Long.fromNumber(888),
};
const tx = Transaction.confirm(txParams, new HTTPProvider("http://my-api.com"));
expect(tx.isConfirmed()).toBeTruthy();
static reject(params: TxParams, provider: Provider): Transaction
Instantiates a Transaction
in Rejected
state.
params
: TxParams
- core fields to initialise the Transaction
with.provider
: Provider
- a Provider
instance.Transaction
- the newly-Instantiated Transaction
.import { HTTPProvider } from "@zilliqa-js/core";
import { Transaction } from "@zilliqa-js/account";
const txParams = {
version: 0,
toAddr: "20_byte_hex_string",
amount: new BN(8),
gasPrice: new BN(100),
gasLimit: Long.fromNumber(888),
};
const tx = Transaction.reject(txParams, new HTTPProvider("http://my-api.com"));
expect(tx.isRejected()).toBeTruthy();
confirm(txHash: string, maxAttempts: number = 33, interval: number = 1000): Promise<Transaction>
Checks whether the Transaction
is confirmed on the blockchain, by verifying
the its receipt
status (boolean
). This method uses an exponential backoff to
poll the lookup node. By default, the number of attempts made is 33, with a
starting interval of 1000ms.
txHash
: string
- the transaction hash to use for polling.maxAttempts
: number = 33
(Optional) - the maximum number of attempts
before setting status as Rejected
.interval
: number = 1000
(Optional) - the initial interval. This grows
exponentially between attempts.Promise<Transaction>
- Transaction
with its status confirmed onchain.import { HTTPProvider } from '@zilliqa-js/core';
import { Transaction } from '@zilliqa-js/account';
// hash can be obtained from CreateTransaction
const my_hash = 'some_known_tx_hash';
conts tx = new Transaction(params, new HTTPProvider('http://my-api.com'));
tx.confirm(some_hash)
.map((tx) => // do something)
.catch((err) => // handle the error);
blockConfirm(txHash: string, maxblockCount: number = 4, interval: number = 1000): Promise<Transaction>
Checks whether the Transaction
is confirmed on the blockchain, by verifying
the its receipt
status (boolean
). This method uses latest blockNumber to get
the transaction receipt, which is more frendily to remote lookup node. By
default, the number of blockCount is 4, with a starting interval of 1000ms. The
member Transaction.blockConfirmation
will count the block numbers during the
process.
txHash
: string
- the transaction hash to use for polling.maxblockCount
: number = 4
(Optional) - the maximum number of block count
before setting status as Rejected
.interval
: number = 1000
(Optional) - the initial interval. This grows
exponentially between attempts.Promise<Transaction>
- Transaction
with its status confirmed onchain.import { HTTPProvider } from '@zilliqa-js/core';
import { Transaction } from '@zilliqa-js/account';
// hash can be obtained from CreateTransaction
const my_hash = 'some_known_tx_hash';
conts tx = new Transaction(params, new HTTPProvider('http://my-api.com'));
tx.blockConfirm(some_hash)
.map((tx) => // do something)
.catch((err) => // handle the error);
map(txHash): Transaction
Maps over the transaction, taking a callback that accepts TxParams
. The user
may freely mutate the Transaction, and will receive the newly-mutated
transaction. The object returned is merged into the target Transaction
.
fn
: (prev: TxParams) => TxParams)
- the transaction hash to use for
polling. exponentially between attempts.Transaction
.import { HTTPProvider } from '@zilliqa-js/core';
import { Transaction } from '@zilliqa-js/account';
// hash can be obtained from CreateTransaction
const my_hash = 'some_known_tx_hash';
let tx = new Transaction(params, new HTTPProvider('http://my-api.com'));
async () => {
try {
tx = await tx.confirm(some_hash);
if (tx.isConfirmed()) {
.map((tx) => {
// do something, but must always return `TxParams`.
// generally, you should avoid performing side effects in `map`.
return tx
});
}
} catch (err) {
// handle this error somehow
}
}();
encodeTransactionProto(tx: TxParams): Buffer
Encodes a transaction with protobuf
and returns its bytes as a Buffer. Used
for providing a payload to signTransaction
.
tx
: TxParams
- plain object containing core transaction fields that must
be used when generating a signature.Buffer
- the bytes of the protobuf
-serialised transaction fields.FAQs
Used for signing transactions.
We found that @zilliqa-js/account demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 6 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.